import fs from 'fs';
import jwt from 'jsonwebtoken';
import { v4 as uuidv4 } from 'uuid';
// import { secretKey } from './config';
import express from 'express';
const secretKey = 'your_secret_key';
const menu = express.Router();

/**
 * 菜单管理
 */
menu.get('/menuList', (req, res) => {
  // 获取请求头中的 token
  const token = req.headers['authorization'];
  const { pageNum = 1, pageSize = 10 } = req.query;
  if (!token) {
    return res.json({
      success: false,
      code: 401,
      message: '未登录',
      data: null
    });
  }
  const menus = JSON.parse(fs.readFileSync('./data/menus.json', 'utf-8'));
  try {
    // 验证 token
    const userInfo = jwt.verify(token, secretKey);
    const { pageNum = 1, pageSize = 10 } = req.query;
    const start = (pageNum - 1) * pageSize;
    const end = start + pageSize;
    res.json({
      success: true,
      code: 100,
      message: '成功',
      data: {
        total: menus.length,
        list: menus.slice(start, end)
      }
    });
  } catch (error) {
    res.json({
      success: false,
      code: 401,
      message: '登录失效',
      data: null
    });
  }

});


// 创建编辑，数据存放到data/menus文件中
menu.post('/update', (req, res) => {
  const menus = JSON.parse(fs.readFileSync('./data/menus.json', 'utf-8'));

  const { _id, ...otherInfo } = req.body;

  // 编辑用户
  if (_id) {
    const menu = menus.find(menu => menu._id === _id);
    if (!menu) {
      return res.status(404).json({ code: 10000, success: false, message: '部门不存在' });
    }
    const menuUpdate = { ...menu, ...otherInfo };
    menus.splice(menus.findIndex(menu => menu._id === _id), 1, menuUpdate);
    fs.writeFileSync('./data/menus.json', JSON.stringify(menus, null, 2), 'utf-8');  // 将数据写入文件
    console.log('menus', menus[0])
    return res.json({ success: true, message: '成功' });
  }
  // 创建用户
  const { parentId } = req.body;
  // 有parentId的时候，是创建子部门，没有parentId的时候是创建顶级部门
  if (parentId) {
    const parentMenu = menus.find(menu => menu._id === parentId);
    if (!parentMenu) {
      return res.status(404).json({ code: 10000, success: false, message: '父部门不存在' });
    }
    // 有parentId的时候，是创建子部门，在children中添加
    const menu = { _id: uuidv4(), parentId, ...otherInfo, createTime: new Date(), updateTime: new Date(), lastLoginTime: new Date() };
    parentMenu.children = parentMenu.children || [];
    parentMenu.children.push(menu);
  }
  fs.writeFileSync('./data/menus.json', JSON.stringify(menus, null, 2), 'utf-8');  // 将数据写入文件

  res.json({ success: true, message: '成功' });
});

// 删除用户
menu.post('/delete', (req, res) => {
  const menus = JSON.parse(fs.readFileSync('./data/menus.json', 'utf-8'));

  const { id } = req.body;
  const delId = (id) => {
    const index = menus.findIndex(menu => menu._id === id);

    if (index === -1) {
      // 那么在children中查找
      menus.forEach(menu => {
        if (menu.children) {
          const childIndex = menu.children.findIndex(child => child._id === id);
          if (childIndex !== -1) {
            menu.children.splice(childIndex, 1);
            fs.writeFileSync('./data/menus.json', JSON.stringify(menus, null, 2), 'utf-8');  // 将数据写入文件
            return res.json({ success: true, message: '成功' });
          }
        }
      })
      return res.json({ success: false, message: '部门不存在' });
    }
    menus.splice(index, 1);
  }
  delId(id);
  // Array.isArray(ids) ? ids.forEach(delId) : delId(ids);
  fs.writeFileSync('./data/menus.json', JSON.stringify(menus, null, 2), 'utf-8');  // 将数据写入文件
  res.json({ success: true, message: '删除部门成功' });
});

export default menu;